from ui.user import Ui_UserMainWindow
from service import *
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QHeaderView
from PyQt5.QtGui import  QStandardItemModel,QStandardItem
import globalvar

class UserMainWindow(Ui_UserMainWindow, QtWidgets.QMainWindow):
    def __init__(self) -> None:
        super().__init__()
        self.setupUi(self)
        self.queryBook()
        self.pushButton.clicked.connect(self.queryBook)
        self.pushButton_2.clicked.connect(self.addBorrow)

    def addBorrow(self):
        selected_rows = self.tableView.selectionModel().selectedRows()
        if selected_rows:
            for index in selected_rows:
                # 获取行号
                row = index.row()
                # 获取模型
                model = index.model()
                # 提取该行所有列的内容
                row_data = [model.data(model.index(row, col)) for col in range(model.columnCount())]
                print(f"选中行 {row} 的内容: {row_data}")
                book_id = row_data[0]
                borrowsvc = BorrowService()
                borrowsvc.borrowBook(globalvar.user_id,book_id)
        else:
            print("没有选中任何行")

    def queryBook(self):
        title = self.lineEdit.text()
        bs = BookService()
        if title:
            book_list = bs.getBookList(title)
        else:
            book_list = bs.getBookList()

        self.model=QStandardItemModel(4,4)#存储任意结构数据
        self.model.setHorizontalHeaderLabels(['id','书名','isbn','作者','可借数量'])
        row = 0
        for u in book_list:
            column = 0
            self.model.setItem(row,column,QStandardItem("%s"%(u.id)))
            self.model.setItem(row,column+1,QStandardItem("%s"%(u.title)))
            self.model.setItem(row,column+2,QStandardItem("%s"%(u.isbn)))
            self.model.setItem(row,column+3,QStandardItem("%s"%(u.author)))
            self.model.setItem(row,column+4,QStandardItem("%s"%(u.count)))
            row += 1
        self.tableView.setModel(self.model)
        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)